<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/3/2
 * Time: 13:26
 */
class AgentAction extends Action{
    //代理商列表
    public function getList($name='',$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $agentModel = M('vendor_agent');
        Session::switchCustomer($customerId);
        $condition["b.customerId"]=array('eq',$customerId);
        $condition["b.agent"]=array('eq','vendoragent');
        $condition["a.deleted"]=array('eq',0);
        isset($name)&&$name?$condition["a.name"]=array('like','%'.$name.'%'):"";
        $result = $agentModel->alias('a')
            ->join('inner join wx_customer_user b on a.fromCustomerUserId=b.id')
            ->join("wx_".$customerId."_user_weixin_info c on a.userId=c.userId")
            ->where($condition)
            ->field('a.*,b.loginName,c.nickname,c.headimgurl')
            ->order('a.createTime desc')
            ->limit($start,$limit)
            ->group("a.id")
            ->select();
        if($result){
            $count = $agentModel->alias('a')
                ->join('inner join wx_customer_user b on a.fromCustomerId=b.id')
                ->where($condition)
                ->field('a.*')
                ->count();
            Output::instance()->objArray($result,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //保存代理商
    public function save($id,$mId,$name,$loginName,$password,$agentAward,$rechargeAward){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        //添加用户
        $customerUserModel=M("customer_user");
        $MimallModel=M("mimall");
        if(!$id) {
            $res=$customerUserModel->where("loginName='" . $loginName . "'")->find();
            if($res && count($res) > 0) {
                Output::instance()->resultCode('1','登录名已经存在！');
                return;
            }
            $userData["loginName"]=$loginName;
        }
        $data["mId"]=0;
        if($password) {
            $userData["password"]=Encryption::password($password);
        }
        $userData["status"] = 'open';
        $userData["agent"]="vendoragent";
        if($id) {
            $userResult=$customerUserModel->where("loginName='" . $loginName . "'")->save($userData);

        } else {
            $userData["customerId"]=$customerId;
            $userResult=$customerUserModel->add($userData);

        }
        $agentModel =   M("vendor_agent");
        if(!$id) {
            $data["fromCustomerUserId"]=$userResult;
        }
        $data["name"]=$name;
        $data["agentAward"]=$agentAward;
        $data['rechargeAward']=$rechargeAward;
        $data["deleted"]=0;
        $data["updateTime"]=date("Y-m-d H:i:s");
        if($id) {
            $result=$agentModel->where("id=$id")->save($data);
        } else {
            $data["createTime"]=date("Y-m-d H:i:s");
            $result=$agentModel->add($data);
        }
        if ($result) {
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }
    /*修改获取单条*/
    public function getAgentById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        $agentModel = M("vendor_agent");

        $where["a.id"]=$id;
        $result=$agentModel->alias('a')->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
            ->field("a.*,b.loginName")
            ->where($where)->find();
        if(!$result['activeQrcode']){
            $imgInfo = WeixinApi::createwxaqrcode("page/channelActivate/channelActivate?id=$id","activeQrcode".date("His").$id.".jpg");
            $activeQrcode = $imgInfo->path;
            $agentModel->where("id=$id")->setField("activeQrcode",$activeQrcode);
            $result['activeQrcode']=$activeQrcode;
        }
        Session::switchCustomer($customerId);
        if ($result) {
            Output::instance()->object($result);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }
    /*删除代理商*/
    public function delete($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        $agentModel = M("vendor_agent");

        $where["id"]=$id;
        $data["deleted"] =1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result=$agentModel->where($where)->save($data);
        if ($result) {
            Output::instance()->object(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
        Session::switchCustomer($customerId);
    }
    //获得代理商关联的供应商
    public function associatedVendors($id,$name=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $agentModel = M("vendor_agent");
        Session::switchCustomer($customerId);
        $condition['a.id']=array('eq',$id);
        $condition['c.customerId']=array('eq',$customerId);
        isset($name)&&$name?$condition['b.name']=array('like','%'.$name.'%'):'';
        $result = $agentModel->alias('a')
            ->join("inner join wx_mivendor b on find_in_set(b.id,a.vendors)")
            ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
            ->where($condition)
            ->field('b.*,c.loginName')
            ->limit($start,$limit)
            ->order('a.createTime desc')
            ->select();
        if($result){
            $count =$agentModel->alias('a')
                ->join("inner join wx_mivendor b on find_in_set(b.id,a.vendors)")
                ->where("a.id=$id")
                ->count();
            Output::instance()->objArray($result,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //重新激活代理商
    public function activationAgain($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $agentModel = M("vendor_agent");
        Session::switchCustomer($customerId);
        $data['userId']=null;
        $data['activationTime']=null;
        $agentModel->where("id=$id")->save($data);
        Output::instance()->resultCode();
    }
    //从代理商中移除供应商
    public function removeVendor($id,$vid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $agentModel = M("vendor_agent");
        $vendorModel = M("mivendor");
        Session::switchCustomer($customerId);
        $agentInfo = $agentModel->where("id=$id")->find();
        $vendors = explode(',',$agentInfo['vendors']);
        $index = array_keys($vendors,$vid);
        $index = $index[0];
        unset($vendors[$index]);
        $vendors = implode(',',$vendors);
        $data['vendors']=$vendors;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $agentModel->where("id=$id")->save($data);
        $vendorData['vendorAgent']=null;
        $vendorData['updateTime']=date("Y-m-d H:i:s");
        $vendorResult = $vendorModel->where("id=$vid")->save($vendorData);
        if($result&&$vendorResult){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //没有被关联的供应商
    public function unAssociatedVendor($start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModel = M("mivendor");
        Session::switchCustomer($customerId);
        $result = $vendorModel->alias("a")
            ->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
            ->field("a.*,b.loginName")
            ->where("a.vendorAgent is NULL and b.customerId = $customerId")
            ->limit($start,$limit)
            ->select();
        if($result){
            $count = $vendorModel->alias("a")
                ->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
               ->where("a.vendorAgent is NULL and b.customerId = $customerId")
                ->count();
            Output::instance()->objArray($result,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //供应商关联到代理商
    public function vendorAssociate($id,$vids){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $agentModel = M("vendor_agent");
        $vendorModel = M("mivendor");
        Session::switchCustomer($customerId);
        $agentInfo = $agentModel->where("id=$id")->find();
        if($agentInfo['vendors']){
            $vids = implode(",",array_merge(explode(",",$agentInfo['vendors']),explode(",",$vids)));
            $data['vendors']=$vids;
        }else{
            $data['vendors']=$vids;
        }
        $data['updateTime']=date("Y-m-d H:i:s");
        $agentResult = $agentModel->where("id=$id")->save($data);
        $vendorData['vendorAgent']=$id;
        $vendorData['updateTime']=date("Y-m-d H:i:s");
        $vendorResult = $vendorModel->where("id in ($vids)")->save($vendorData);
        if($agentResult&&$vendorResult){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }

}